<?php

/**
 * 购物车管理
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2016/10/8
 * Time: 15:03
 */
class Api_ShopCart extends PhalApi_Api
{

    public function getRules()
    {
        return [
            'add' => [
                'uid' => ['name' => 'uid', 'type' => 'int', 'require' => false,  'desc' => '用户id'],
                'sid' => ['name' => 'sid', 'type' => 'int', 'require' => false,  'desc' => '商家id'],
                'number' => ['name' => 'number', 'type' => 'int',  'require' => false, 'desc' => '数量'],
                'gid' => ['name' => 'gid', 'type' => 'string',  'require' => false,  'desc' => '商品id'],
                'nature_val' => ['name' => 'nature_val', 'type' => 'array', 'require' => false, 'format' => 'json', 'desc' => '更新参数值/["属性id","属性id","属性id"]'],
                'price' => ['name' => 'price', 'type' => 'string', 'require' => false,  'desc' => '价钱'],
            ],
            'getList' => [
                'uid' => ['name' => 'uid', 'type' => 'int',  'require' => true,  'desc' => '用户id'],
            ],
            'getListTest' => [
                'uid' => ['name' => 'uid', 'type' => 'int',  'require' => true,  'desc' => '用户id'],
            ],
            'updateData' => [
                'id' => ['name' => 'id', 'type' => 'int', 'require' => true, 'desc' => '购物车id'],
                'number' => ['name' => 'number', 'type' => 'int', 'require' => false,  'desc' => '数量'],
                'parameter' => ['name' => 'parameter', 'type' => 'array', 'require' => true, 'format' => 'json', 'desc' => '更新参数'],
            ],
            'delete' => [
                'uid' => ['name' => 'uid', 'type' => 'int',  'require' => true,  'desc' => '用户id'],
                'ids' => ['name' => 'ids', 'type' => 'array', 'format' => 'explode', 'require' => true, 'separator' => ',', 'desc' => '购物车id,可删除一个或者多个']
            ],
            'count' => [
                'uid' => ['name' => 'uid', 'type' => 'int', 'require' => true, 'desc' => '用户id'],
            ],
            'updateNumber' => [
                'id' => ['name' => 'id', 'type' => 'int',  'require' => true,  'desc' => '购物车id'],
                'number' => ['name' => 'number', 'type' => 'int', 'min' => 1, 'require' => true,  'desc' => '数量'],
            ],
            'confirmOrderInfo' => [
                'uid' => ['name' => 'uid', 'type' => 'int',  'require' => true, 'desc' => '用户id'],
                'status' => ['name' => 'status', 'type' => 'int',  'require' => true, 'desc' => '0是立即购买 / 1是购物车'],
                'parameter' => ['name' => 'parameter', 'type' => 'array', 'require' => true, 'format' => 'json', 'desc' => '0的格式{"sid":[shopCartId,shopCartId,..]} / 1的格式{"sid":35,"gid":181,"nature_val":[属性值id,属性值id]}'],
            ],
            'getSidNature' => [
                'shopId' => ['name' => 'shopId', 'type' => 'int', 'require' => true, 'desc' => '购物车Id'],
            ],
            'a' => [
                'parameter' => ['name' => 'parameter', 'type' => 'array', 'require' => true, 'format' => 'json', 'desc' => '更新参数'],
            ]
        ];
    }

    /**
     * 添加购物车
     * @desc 添加购物车
     * @return boolean isAdd 成功返回购物车的id,失败返回false
     * @return string count 表示用户所有购物车数量
     * @return boolean isUpdate true表示更新成功,false表示失败
     */
    public function add()
    {

        $shopCart = new Domain_ShopCart();
        $shelves = new Model_Shelves();
        $products = new Domain_HomePageProducts();
        sort($this->nature_val);
        $field = 'id,nature_val,number';
        $arg = [
            'uid' => $this->uid,
            'sid' => $this->sid,
            'zixc_bikeshop_goods_id' => $this->gid,
            'isDisplay' => 1
        ];

        $nature_val = $shopCart->getByIdUid($field, $arg);

        foreach ($nature_val as $k => $v) {

            //如果存在就更新number 字段
            if (!array_diff($this->nature_val, json_decode($nature_val[$k]['nature_val']))) {
                $field2 = [
                    'id' => $nature_val[$k]['id']
                ];

                $number = [
                    'number' => $this->number ? $this->number + $nature_val[$k]['number'] : $nature_val[$k]['number'] + 1
                ];

                $rs = $shopCart->updateNumber($field2, $number);  //更新number字段

                if ($rs) {
                    //统计购物车总数
                    $count = $shopCart->countShopCart($this->uid);
                }
                //更新库存
                $arg2 = [
                    '`values`' => json_encode($this->nature_val, JSON_UNESCAPED_UNICODE),
                    'g_id' => $this->gid
                ];
                $id = $products->getDataByFieldSku('id', $arg2);//sku id值
                $editArg = [
                    'sid' => $this->sid,
                    'gid' => $this->gid,
                    'nature_val' => $id['id'],
                    'number' => 1
                ];

                $shelves->editNumberTwo($editArg);
                return [
                    'isUpdate' => $rs ? true : false,
                    'count' => $count['0']["SUM(number)"] ? $count['0']["SUM(number)"] : 0
                ];
                //
            }
        }
        $data = [
            'sid' => $this->sid,
            'uid' => $this->uid,
            'zixc_bikeshop_goods_id' => $this->gid,
            'nature_val' => json_encode($this->nature_val),
            'price' => $this->price,
            'date' => date('Y-m-d H:i:s'),
            'isShopcart' => 1
        ];

//        return $data;

//        DI()->logger->debug('购物车添加的数据$data', $data);

        $rs = $shopCart->shopCart($data);
        //更新库存
        $arg2 = [
            '`values`' => json_encode($this->nature_val, JSON_UNESCAPED_UNICODE),
            'g_id' => $this->gid
        ];
        $id = $products->getDataByFieldSku('id', $arg2);//sku id值

        $editArg = [
            'sid' => $this->sid,
            'gid' => $this->gid,
            'nature_val' => $id['id'],
            'number' => 1
        ];

        $shelves->editNumberTwo($editArg);

        if ($rs) {
            //统计购物车总数
            $count = $shopCart->countShopCart($this->uid);
        }

        return [
            'isAdd' => $rs ? $rs['id'] : false,
            'count' => $count['0']["SUM(number)"] ? $count['0']["SUM(number)"] : 0
        ];
    }

    /**
     * 统计购物车数量
     * @desc 统计购物车数量
     * @return string count 表示用户所有购物车数量
     */
    public function count()
    {
        $shopCart = new Domain_ShopCart();
        $count = $shopCart->countShopCart($this->uid);

        return [
            'count' => $count['0']["SUM(number)"]
        ];
    }

    /**
     * @return array
     */
    public function getListTest()
    {
        //根据uid 获取sid和title值
        $shop = new Domain_HomePageShop();
        $shopCart = new Domain_ShopCart();
        $product = new Domain_HomePageProducts();
        $listData = $shopCart->getList($this->uid); //根据uid获取列表内容

        if (!$listData) {
            return $rs = [];
        }

        //循环购物车列表
        foreach ($listData as $k => $v) {
            $listData[$k]['nature_val'] = json_decode($listData[$k]['nature_val'], true);
            $newRs[] = $shop->getBySidTitle($v['sid']);      //根据sid获取title组合
            $rs = DI()->helper->formatArray($newRs);  //删除数组中相同元素，只保留一个相同元素
            $result = DI()->helper->formatArr2($listData, 'sid'); //如果两个数组sid相同,就合并成一个数组
        }


        //循环列表,取出id和nature值作为查询条件
        foreach ($result as $k2 => $v2) {
            foreach ($v2 as $k3 => $v3) {
                $a[] = [
                    'id' => $v3['id'],
                    'nature_val' => $v3['nature_val'],
                ];
            }
        }

        //循环条件,查询出属性值
        foreach ($a as $k4 => $v4) {
            $arg = [
                'id' => $v4['nature_val'],
            ];
            $natureVal[$v4['id']] = $product->getByIdUidNatureVal($arg);//属性值
        }

        //通过属性值中的n_id条件,查询属性名
        foreach ($natureVal as $k5 => $v5) {
            $nid = array_column($v5, 'n_id');
            $natureName[$k5] = $product->getByNIdNature($nid);//属性名
        }

        //判断名和值的条件,并加入到名中 名:值
        foreach ($natureName as $k6 => $v6) {
            foreach ($natureVal as $k7 => $v7) {
                foreach ($v6 as $k8 => $v8) {
                    foreach ($v7 as $k9 => $v9) {
                        if ($v8['id'] == $v9['n_id'] && $k6 == $k7) {
                            $v9['nature_val'] = ':' . $v9['nature_val'];
                            $natureName[$k6][$k8]['nature'] .= $v9['nature_val'];
                        }
                    }
                }
            }
        }


        //取出新生成的属性值
        foreach ($natureName as $k10 => $v10) {
            foreach ($v10 as $k11 => $v11) {
                $new[$k10][] = $v11['nature'];
            }
        }

        //返回出来的是个数组,分割成数组并用 符号链接
        foreach ($new as $k12 => $v12) {
            $newA[$k12] = implode(';', $v12); //分割后的字符串
        }

        //循环之前的列表,判断id是否相同, true 则加入其中
        foreach ($newA as $k13 => $v13) {
            foreach ($result as $k14 => $v14) {
                foreach ($v14 as $k15 => $v15) {
                    if ($k13 == $v15['id']) {
                        $result[$k14][$k15]['content'] = $newA[$k13];
                    }
                }
            }
        }

        //最后循环rs和result 判断 id==sid
        foreach ($rs as $k2 => $v2) {
            foreach ($result as $k3 => $v3) {
                foreach ($v3 as $k4 => $v4) {
                    if ($v2['id'] == $v4['sid']) {
                        $rs[$k2]['shopDetails'][] = $v4;
                    }
                }
            }
        }


        return $rs;
    }

    /**
     * 订单信息
     * @desc 订单信息
     */
    public function confirmOrderInfo()
    {

        $shop = new Domain_HomePageShop();
        $shopCart = new Domain_ShopCart();
        $product = new Domain_HomePageProducts();

//        DI()->logger->debug('订单信息Json',$this->parameter);
        $a = json_encode($this->parameter);
        $request = json_decode($a, true);
//        return $request;
        $rs = [];
        $a = [];
//        $status = 1 为购物车;
        if ($this->status) {
//            {"35":[160,147]}
            foreach ($request as $k => $v) {
                $rs['goods'][] = $shop->getBySidAddress($k);  //根据门店id,查询查询id,title,address的值
                $kData[] = $k; //门店id
            }
            foreach ($kData as $v16) {
                $id[] = $request[$v16];  // 170
                $listData = $shopCart->getBYUidIdSId($id, $this->uid);//根据商品id,查询购物车和商品
            }

            //循环购物车列表
            foreach ($listData as $k17 => $v17) {
                $listData[$k17]['nature_val'] = json_decode($listData[$k17]['nature_val'], true);
                $result = DI()->helper->formatArr2($listData, 'sid'); //如果两个数组sid相同,就合并成一个数组
            }

            foreach ($result as $k2 => $v2) {
                foreach ($v2 as $k3 => $v3) {
                    $a[] = [
                        'id' => $v3['id'],
                        'nature_val' => $v3['nature_val'],
                    ];
                }
            }
//            return $a;
        } else {
            //{"sid":35,"gid":181,"nature_val":[160,147]}
            $rs['goods'][] = $shop->getBySidAddress($request['sid']);  //根据门店id,查询查询id,title,address的值
            $price = $product->getByIdDetails($request['gid'],'retail_price');
            $field = 'id,title,earnest,retail_price,image_url';
            $arg = [
                'id' => $request['gid']
            ];
            $listData = $product->search($field, $arg);
            $listData[0]['sid'] = $request['sid'];
            $listData[0]['number'] = 1;
            $listData[0]['price'] = $listData[0]['retail_price'];
            $listData[0]['gid'] = $listData[0]['id'];
            unset($listData[0]['retail_price']);
            $result[0] = $listData;
            $a[] = [
                'id' => $request['gid'],
                'nature_val' => $request['nature_val'],
            ];

            sort($request['nature_val']);
            $data = [
                'sid' => $request['sid'],
                'uid' => $this->uid,
                'zixc_bikeshop_goods_id' => $request['gid'],
                'nature_val' => json_encode($request['nature_val']),
                'price' => $price['retail_price'],
                'date' => date('Y-m-d H:i:s'),
                'isShopcart' => 0,
                'isDisplay' => 0,
            ];


            $shopCartId = $shopCart->shopCart($data);
            $result[0][0]['id'] = $shopCartId['id'];
        }

//        return $result;

        //循环条件,查询出属性值
        foreach ($a as $k4 => $v4) {
            $arg = [
                'id' => $v4['nature_val'],
            ];
            $natureVal[$v4['id']] = $product->getByIdUidNatureVal($arg);//属性值
        }

        //通过属性值中的n_id条件,查询属性名
        foreach ($natureVal as $k5 => $v5) {
            $nid = array_column($v5, 'n_id');
            $natureName[$k5] = $product->getByNIdNature($nid);//属性名
        }

        //判断名和值的条件,并加入到名中 名:值
        foreach ($natureName as $k6 => $v6) {
            foreach ($natureVal as $k7 => $v7) {
                foreach ($v6 as $k8 => $v8) {
                    foreach ($v7 as $k9 => $v9) {
                        if ($v8['id'] == $v9['n_id'] && $k6 == $k7) {
                            $v9['nature_val'] = ':' . $v9['nature_val'];
                            $natureName[$k6][$k8]['nature'] .= $v9['nature_val'];
                        }
                    }
                }
            }
        }

        //取出新生成的属性值
        foreach ($natureName as $k10 => $v10) {
            foreach ($v10 as $k11 => $v11) {
                $new[$k10][] = $v11['nature'];
            }
        }

        //返回出来的是个数组,分割成数组并用 符号链接
        foreach ($new as $k12 => $v12) {
            $newA[$k12] = implode(';', $v12); //分割后的字符串
        }
//        return $result;
//        return $newA;

        if($this->status){
            //循环之前的列表,判断id是否相同, true 则加入其中
            foreach ($newA as $k13 => $v13) {
                foreach ($result as $k14 => $v14) {
                    foreach ($v14 as $k15 => $v15) {
                        if ($k13 == $v15['id']) {
                            $result[$k14][$k15]['content'] = $newA[$k13];
                        }
                    }
                }
            }
        }else{
            //循环之前的列表,判断id是否相同, true 则加入其中
            foreach ($newA as $k13 => $v13) {
                foreach ($result as $k14 => $v14) {
                    foreach ($v14 as $k15 => $v15) {
                        if ($k13 == $v15['gid']) {
                            $result[$k14][$k15]['content'] = $newA[$k13];
                        }
                    }
                }
            }
        }



        //判断sid是否相同,相同就加入同一个数组
        foreach ($rs['goods'] as $k18 => $v18) {
            foreach ($result as $k19 => $v19) {
                foreach ($v19 as $k20 => $v20) {
                    if ($v20['sid'] == $v18['id']) {
                        $rs['goods'][$k18]['shopDetails'] = $v19;
                    }
                }

            }
        }


        return $rs;
    }


    /**
     * 更新购物车属性
     * $desc 更新购物车尺寸/颜色/速别/数量/是否选中的属性
     * @return int code true表示添加成功,false表示失败
     */
    public function updateData()
    {
        $shopCart = new Domain_ShopCart();

        $field = 'id,number,sid,uid,zixc_bikeshop_goods_id,nature_val';
        $arg = [
            'id' => $this->id,
        ];

        $nature_val = $shopCart->getByIdUid($field, $arg);

        //如果修改的值与数据库中的相同,就删除修改的
        foreach ($nature_val as $k => $v) {
            $arg2 = [
                'sid' => $v['sid'],
                'uid' => $v['uid'],
                'zixc_bikeshop_goods_id' => $v['zixc_bikeshop_goods_id'],
                'nature_val' => json_encode($this->parameter)
            ];

            $nature = $shopCart->getByIdUid('id,nature_val', $arg2);
        }

        foreach ($nature as $k2 => $v2) {

            if (!array_diff($this->parameter, json_decode($v2['nature_val'])) && !($v2['id'] == $this->id)) {
                $shopCart->deleteData($this->id);
                return false;

            }
        }

        $data = [
            'nature_val' => json_encode($this->parameter, JSON_UNESCAPED_UNICODE),
            'number' => $this->number
        ];

        $rs = $shopCart->updateData($this->id, $data);
        return $rs ? true : false;
    }

    /**
     * 修改购物车数据
     */
    public function updateNumber()
    {
        $shopCart = new Domain_ShopCart();

        $number = [
            'number' => $this->number
        ];

        $rs = $shopCart->updateNumber($this->id, $number);

        return $rs ? true : false;
    }

    /**
     * 购物车删除
     * @desc 购物车删除
     * @return int isDelete true表示添加成功
     * @throws -1403 非法用户删除数据
     */
    public function delete()
    {
        $shopCart = new Domain_ShopCart();

        $count = count($this->ids);
        DI()->logger->debug('购物车删除数据:', json_encode($this->ids));


        for ($i = 0; $i < $count; $i++) {
            $rs[] = $shopCart->deleteData($this->ids[$i]);
        }

        $number = $shopCart->countShopCart($this->uid);  //统计购物车总数
        DI()->logger->debug('购物车删除后的数量:', $number['0']["SUM(number)"]);

        return [
            'isDelete' => $rs ? true : false,
            'count' => $number['0']["SUM(number)"] ? $number['0']["SUM(number)"] : '0'
        ];
    }

    /**
     * 获取商品的属性值
     * @desc 根据商品所在的门店id,获取对应的属性值
     * @return string nature 属性名
     * @return array details 商品属性详细信息
     * @return string details.valueID 属性名id
     * @return string details.value 属性值
     */
    public function getSidNature()
    {
        $shopCart = new Domain_ShopCart();
        $product = new Domain_HomePageProducts();

        $listData = $shopCart->getByIdNature($this->shopId); //根据uid获取当前列表内容


        if (!$listData) {
            return false;
//            return '查询不到数据';
        }

        $nat_val = json_decode($listData['nature_val']); //当前选择
        $field = '`id`,`retail_price`,`images`,`values`';
        $arg = [
            '`values`' => json_encode($nat_val),
        ];
        $skuData = $product->getDataByFieldSku($field, $arg);
        $data['image'] = $skuData['images'];
        $data['retail_price'] = $skuData['retail_price'];
        $shelveId = $product->getDataByFieldSku('id', ['g_id' => $listData['zixc_bikeshop_goods_id'], '`values`' => $skuData['values']]);
        if (!$shelveId) {
            return false;
        }
        $numberSSS = $product->getByIdSidNumber('number', $shelveId['id']);
        $data['sum'] = $numberSSS['number'];

        $arg = [
            'sid' => $listData['sid'],
            'gid' => $listData['zixc_bikeshop_goods_id']
        ];

        $shelvesData = $product->getByIdSidNatureVal('nature_val', $arg); //上架的数据

        foreach ($shelvesData as $k12) {

            $sku_a = $product->getSku($k12['nature_val']); //查询sku值

            $nat_val_a = json_decode($sku_a['values']);

            foreach ($nat_val_a as $v13) {

                $values_a = $product->getByIdUidNatureVal(['id' => $v13]);

                $nature_a[] = $values_a[0]['n_id'];

                $nature_val_a[] = $values_a[0];

            }

        }
        $nature_all = array_unique($nature_a);
        $nature_val_all = DI()->helper->array_unique_fb($nature_val_a);

        //拼接属性值和名
        foreach ($nature_all as $k2) {
            $natu_val = array();
            $nature_name = $product->getByNIdNature($k2);
            foreach ($nature_val_all as $ke) {
                if ($ke[1] == $k2) {
                    $natu_val[] = array(
                        'valueID' => $ke[0],
                        'value' => $ke[2],
                    );
                }
            }

            $date[] = array(
                'nature' => $nature_name[0]['nature'],
                'details' => $natu_val,
            );
        }

        foreach ($nat_val as $k13 => $v13) {
            foreach ($date as $k14 => $v14) {
                foreach ($v14['details'] as $k15 => $v15) {
                    if ($v13 == $v15['valueID']) {
                        $date[$k14]['default'] = $v15['value'];
                    }
                }
            }
        }


        //拼接content
        $arg = [
            'id' => $nat_val, //购物车参数
        ];

        $natureVal = $product->getByIdUidNatureVal($arg);//属性值

        //通过属性值中的n_id条件,查询属性名
        foreach ($natureVal as $k5 => $v5) {
            $nid = $v5['n_id'];
            $natureName[] = $product->getByNIdNature($nid);//属性名
        }

        //判断名和值的条件,并加入到名中 名:值

        foreach ($natureName as $k6 => $v6) {
            foreach ($natureVal as $k7 => $v7) {
                foreach ($v6 as $k8 => $v8) {
                    if ($v8['id'] == $v7['n_id'] && $k6 == $k7) {
                        $v7['nature_val'] = ':' . $v7['nature_val'];
                        $natureName[$k6][$k8]['nature'] .= $v7['nature_val'];
                    }
                }
            }
        }

        //取出新生成的属性值
        foreach ($natureName as $k10 => $v10) {
            foreach ($v10 as $k11 => $v11) {
                $new[] = $v11['nature'];
            }
        }

        $newA = implode(';', $new); //分割后的字符串
        $data['datas'] = $date;
        $data['number'] = $listData['number'];
        $data['sid'] = $listData['sid'];
        $data['gid'] = $listData['zixc_bikeshop_goods_id'];
        $data['content'] = $newA;
        return $data;
    }

}
